<template>
  <div class="queue-wrap">
    <continer :showPage="showPage" :isNoTabs="true" :isShowTree="isShowFilter">
      <template slot="tree">
        <draggable @end="onDragover(1)" v-model="filterArr">
          <div v-for="(item,index) in filterArr" :key="index" class="filter-item" :class="{'active-filter': item.filterId === currentFilterOpr.filterId}" @click="currentFilter(item)">
            <div class="filter-name"><i class="V7_iconfont V7_iconV7tubiao_yidong yidong-style"></i>{{item.filterName}}</div>
          </div>
        </draggable>
      </template>
      <template slot="search">
        <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryList"></QuickSearch>
      </template>
      <template slot="oprate">
        <commonFilter
          :filterType="5"
          :filterFieldList="filterFieldList"
          :modelId="$route.params.modelId || $route.query.modelId"
          :filterConfigId="currentFilterOpr.filterId"
          @common-filter="filterSearch"
        ></commonFilter>
        <!-- <conditionFilter :filterFieldList="filterFieldList" @search="ordinaryFilterSearch" @search-close="filterSearchClose" ref='conditionFilterRef' class="margin-l-16 condition-filter"></conditionFilter> -->
        <el-button type="primary" size="mini" style="margin-left: 10px" @click="queryList">查询</el-button>
      </template>
      <template slot="content">
        <div class="is-show">
          <el-tooltip effect="dark" :content="isShowFilter ? '隐藏过滤器' : '显示过滤器'" placement="right">
            <i class="V7_iconfont icon-style" :class="[isShowFilter ? 'V7_iconV7tubiao_shouqi' : 'V7_iconV7tubiao_zhankai']" @click="expandCollapse"></i>
          </el-tooltip>
        </div>
        <instiutionTable ref="tableRef"
                         class="instiutionTable"
                         :pages="queueTablePages"
                         :instiutionTableData="queueTableData"
                         :instiutionTableHeader="queueTableHeader"
                         :isCustomerCol="true"
                         :customerTableHeader="customerTableHeader"
                         @headrChange="handleHeaderChange"
                         @batchClick="batchClick"
                         :batchOperate="batchOperate"
                         @sizeChange="sizeChange"
                         @currentChange="currentChangeFun">
                         <template #source="{ scope }">
                           {{ sourceMap[scope.row.source] }}
                         </template>
                        <template #orderStatus="{ scope }">
                          <span class="order-status" :style="{border: '1px solid ' + orderStatusMap[scope.row.orderStatus].color, color: orderStatusMap[scope.row.orderStatus].color}">{{ orderStatusMap[scope.row.orderStatus].name }}</span>
                        </template>
                        <template #currentSlaStatus="{ scope }">
                          <div>
                            <span :class="{overtime: scope.row.currentSlaStatus === 1, noovertime: scope.row.currentSlaStatus === 2, unmatch: scope.row.currentSlaStatus === 3}">{{slaMap[scope.row.currentSlaStatus]}}</span>
                          </div>
                        </template>
                        <template #entireSlaStatus="{ scope }">
                          <div>
                            <span :class="{overtime: scope.row.entireSlaStatus === 1, noovertime: scope.row.entireSlaStatus === 2, unmatch: scope.row.entireSlaStatus === 3}">{{slaMap[scope.row.entireSlaStatus]}}</span>
                          </div>
                        </template>
                         <template #oper="{ scope }">
                           <span class="opera-span" @click.stop="handleEdit(scope.row)">查看</span>
                           <span class="opera-span danger" @click.stop="handleDel(scope.row)" v-if="canDelete">删除</span>
                         </template>
        </instiutionTable>
      </template>
      <template slot="page">
        <editBusiness :isOnlyShow="isOnlyShow" :isShowRule="isShowRule" :currentFilterOpr="currentFilterOpr" :filterBtn="filterBtn" @success="queryList" :agentList="agentListArr" @saveFun="saveFun" @cancelFun="back" ref="addOrEditBusinessRef" @editSuccess="editSuccess" @pageBack="pageBack">
          <template slot="noShowOperateBtn" v-if="currentFilterOpr">
            <template v-if="!filterBtn">
                <el-button size="mini" v-if="currentFilterOpr.updateMaster" @click="transferWorkOrder">调整当前处理人</el-button>
                <el-button size="mini" v-if="currentFilterOpr.terminal" @click="TerminateWorkOrder">终止工单</el-button>
              </template>
          </template>
            <template slot="showOperateBtn" v-if="currentFilterOpr">
              <template v-if="!filterBtn">
                <el-button size="mini" type="primary" v-if="currentFilterOpr.update" @click="editWorkOrder">编辑工单</el-button>
              </template>
              <template v-if="filterBtn">
                <el-button size="mini" v-if="currentFilterOpr.update" @click="cancelWorkOrder">取消</el-button>
                <el-button size="mini" type="primary" v-if="currentFilterOpr.update" @click="updateWorkOrder">提交</el-button>
              </template>
          </template>
        </editBusiness>
      </template>
    </continer>
    <el-dialog class="mp-micro" title="批量导出" :append-to-body="false" :wrapperClosable="false" :modal-append-to-body="false" :visible.sync="dialogVisible" width="560px">
      <div class="export-title">请选择导出字段</div>
      <div class="export-content">
        <div class="left">
          <div class="left-nav">
            <div class="tab-item" :class="tab === 1 ? 'tab-acitve' : ''" @click.stop="changeTab(1)">工单字段</div>
            <div class="tab-item" :class="tab === 2 ? 'tab-acitve' : ''" @click.stop="changeTab(2)">其他信息</div>
          </div>
          <div v-if="tab === 1" class="padding-16">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="businessList" @change="handleCheckedBusinessChange">
              <el-checkbox v-for="item in busOptions" :label="item.businessId" :key="item.businessId">{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <template v-if="tab === 2">
            <el-checkbox-group v-model="otherList" @change="getCheckedList" class="padding-16">
              <el-checkbox label="estimateStatus">满意度</el-checkbox>
            </el-checkbox-group>
          </template>
        </div>
        <i class="center V7_iconfont V7_iconV7tubiao_gengduojiantou"></i>
        <div class="right padding-16">
          <draggable :list="checkedList" group="colors" handle=".move" @drop.native.stop.prevent="">
            <div v-for="(item, index) in checkedList" :key="index" class="list-item">
              <template v-if="optionsMap[item]">
                <i class="V7_iconfont V7_iconV7tubiao_yidong move pointer"></i>
                <span>{{optionsMap[item].name}}</span>
                <i class="V7_iconfont V7_iconV7tubiao-109 pointer" @click="deleteItem(item)"></i>
              </template>
            </div>
          </draggable>
        </div>
      </div>
      <div class="export-title" style="margin-top: 16px">备注</div>
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model="remark"
        maxlength="200"
        show-word-limit
      >
      </el-input>
      <template v-slot:footer>
        <el-button @click.stop="handleExportFields" size="small">使用上一次导出字段</el-button>
        <el-button @click.stop="dialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click.stop="submitSave" size="small" class="primary">导出</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref, Watch, Mixins } from 'vue-property-decorator'
import { deepClone, commonAction, checkHideTel } from '@/utils/common'
import { checkPermission } from '@/utils/directive'
import { CommonModule } from '@/store/modules/common'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import editBusiness from '../components/editBusiness.vue'
import { businessStore } from '../store/business'
import { filterFieldAllList, exportFieldList } from '../utils/staticData'
import conditionFilter from '@/afterSales/components/conditionFilter/index.vue'
import workerOrder from '@/afterSales/views/business/mixins/workerOrder'
import commonFilter from '@/afterSales/components/commonFilter/commonFilter.vue'
import cloneDeep from 'lodash/cloneDeep';
import draggable from 'vuedraggable';
@Component({
  name: 'busAll',
  components: {
    conditionFilter,
    QuickSearch,
    instiutionTable,
    editBusiness,
    continer,
    commonFilter,
    draggable
  }
})
export default class Queue extends Mixins(workerOrder) {
  [x: string]: any

  private tab = 1
  private checkAll = false
  private isIndeterminate = true
  private otherList = [] as any
  private businessList = [] as any
  private remark = ''
  private dialogVisible = false
  private showPage: boolean = false
  private cacheFilter: any[] = [];
  @Ref() private readonly addOrEditBusinessRef !: editBusiness
  @Ref() private readonly tableRef !: instiutionTable
  private filterArr = [] // 当前过滤器组
  private currentFilterOpr: any = {} // 点击的当前视图数据
  private fields = []
  private canDelete = false
  private isOnlyShow = true
  private filterBtn = false
  private isShowRule = true
  private checkedList = [] as any
  private quickSearchForm = {
    form: {
      orderNo: '',
      customerNameOrPhone: '',
      customerContactPhone: ''
    },
    advSearchOptions: [
      { label: '工单编号', inputType: 'input', placeholder: '请输入工单编号', name: 'orderNo' },
      { label: '客户名称/手机号', inputType: 'input', placeholder: '请输入客户名称/手机号', name: 'customerNameOrPhone' },
      { label: '客户联系人手机号', inputType: 'input', placeholder: '请输入联系人手机号', name: 'customerContactPhone' }
    ]
  }

  private getCheckedList () {
    this.checkedList = this.businessList.concat(this.otherList)
  }

  private get busOptions () {
    return [...exportFieldList, ...this.fields.filter((item: any) => {
      const filterArr = ['associateService', 'associateSpare', 'associateUser', 'group']
      return !filterArr.includes(item.fieldType)
    }).map(item => {
      const obj: any = item
      obj.exportFieldType = 1
      return obj
    })]
  }

  private get optionsMap (): any {
    const arr = this.busOptions.concat([{ exportFieldType: 3, name: '满意度', businessId: 'estimateStatus' }])
    const obj = {}
    arr.forEach(item => {
      obj[item.businessId] = item
    })
    return obj
  }

  private get filterFieldList () {
    return [...filterFieldAllList, ...this.customerFieldList]
  }

  private batchOperate = [] as any
  private customerFieldList = [] as any

  private title = ''
  private isShowFilter = 1 // 过滤器默认展开

  private queueTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private customColMap: any = {}
  private selectedArr = []

  private changeTab (tab: number) {
    this.tab = tab
  }

  private queueTableData = []
  private slaMap: any = {
    1: '已超时',
    2: '未超时',
    3: '未匹配'
  }

  private originHeader: any[] = [
    { label: '工单编号', prop: 'orderNo', show: true },
    { label: '创建时间', prop: 'createTime', show: true },
    { label: '创建人', prop: 'createUser', show: true },
    { label: '工单状态', prop: 'orderStatus', custom: true, show: true },
    { label: '工单类型', prop: 'orderCategory', show: true },
    { label: '当前节点', prop: 'activityName', show: true },
    { label: '当前处理人', prop: 'master', show: true },
    { label: '客户名称', prop: 'customerNameVO', show: true },
    { label: '客户手机号', prop: 'customerPhoneVO', show: false },
    { label: '联系人手机号', prop: 'contactPhoneVO', show: false },
    { label: '工单来源', prop: 'source', custom: true, show: true },
    { label: '更新时间', prop: 'updateTime', show: false },
    { label: '当前SLA', prop: 'currentSlaStatus', custom: true, show: true },
    { label: '整体SLA', prop: 'entireSlaStatus', custom: true, show: true }
  ]

  public handleHeaderChange (val) {
    const row = val.filter(item => {
      return item.prop
    }).map(item => {
      return {
        businessId: item.prop,
        isShow: item.show ? 1 : 0
      }
    })
    if (this.originColId) {
      commonAction({
        url: '/server-work/action/view/update',
        method: 'post',
        data: {
          columnType: 5,
          showRow: row,
          id: this.originColId,
          modelId: this.$route.params.modelId || this.$route.query.modelId,
          filterConfigId: this.currentFilterOpr.filterId
        }
      }).then(res => {
        if (!res.success) {
          this.$message.error(res.message)
        }
      })
    }

    this.$nextTick(() => {
      this.queueTableHeader = val.filter(item => item.show)
      this.queueTableHeader.unshift({ type: 'select' })
      this.queueTableHeader.push({ label: '操作', prop: 'oper', custom: true, fixed: 'right', width: '120px', align: 'center' })
      this.queryList()
      // 处理操作列
    })
  }

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name })
    }
    return agentsArr
  }

  private handleCheckedBusinessChange (value) {
    const checkedCount = value.length;
    this.checkAll = checkedCount === this.busOptions.length;
    this.isIndeterminate = checkedCount > 0 && checkedCount < this.busOptions.length;
    const checkedListNew = this.checkedList.filter(item => {
      return item !== 'estimateStatus'
    })
    if (checkedListNew.length < checkedCount) {
      this.checkedList.push(value[value.length - 1])
    } else {
      for (let i = 0; i < checkedListNew.length; i++) {
        if (value.indexOf(checkedListNew[i]) < 0) {
          this.checkedList.splice(i, 1)
        }
      }
    }
  }

  private handleCheckAllChange (val) {
    this.businessList = val ? this.busOptions.map(item => {
      return item.businessId
    }) : []
    this.isIndeterminate = false
    this.getCheckedList()
  }

  private deleteItem (val) {
    if (val === 'estimateStatus') {
      this.otherList = []
    } else {
      this.businessList.map((item, index) => {
        if (item === val) {
          this.businessList.splice(index, 1)
        }
      })
    }
    this.checkedList.map((item, index) => {
      if (item === val) {
        this.checkedList.splice(index, 1)
      }
    })
  }

  private submitSave () {
    let sendData = {}
    if (!this.checkedList.length) {
      this.$message.error('请至少选择一个字段！')
      return false
    }
    const arr = this.checkedList.map(item => {
      if (this.optionsMap[item]) {
        const obj = {
          exportFieldType: (this.optionsMap[item] as any).exportFieldType,
          fieldDesc: (this.optionsMap[item] as any).name,
          fieldName: item
        }
        return obj
      } else {
        return 'undefined'
      }
    }).filter(item => {
      return item !== 'undefined'
    })
    console.log(arr)
    if (typeof this.selectedArr === 'object') { // 单个操作，传ids
      sendData = { remark: this.remark, fieldList: arr, filterId: this.currentFilterOpr.filterId, orderIds: this.selectedArr || [], modelId: this.$route.params.modelId || this.$route.query.modelId }
    } else { // 全选传查询条件
      sendData = {
        remark: this.remark,
        fieldList: arr,
        filterId: this.currentFilterOpr.filterId,
        modelId: this.$route.params.modelId || this.$route.query.modelId,
        filters: this.cacheFilter,
        ...this.quickSearchForm.form
      }
    }
    commonAction({
      url: '/server-work/action/workOrder/export/createExportTask',
      method: 'post',
      data: sendData
    }).then(res1 => {
      if (res1.success) {
        const h = this.$createElement;
        this.businessList = []
        this.otherList = []
        this.checkedList = []
        this.$message({
          message: h('div', {}, [
            h('span', {}, '导出任务进入排队，请前往传输中心查看 '),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'color: 008BEE' }, '立即查看'),
            h('span', { on: { click: this.delMessage }, class: 'V7_iconfont V7_iconV7tubiao_guanbi', style: 'display: inline-block; font-size: 12px; color: #303753;margin-left: 10px;cursor: pointer;' })
          ]),
          type: 'success'
        });
        this.dialogVisible = false
      }
    })
  }

  private delMessage () {
    this.$message.closeAll()
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    this.$router.push('/transmission_center/index/tx_export_task')
  }

  private handleExportFields () {
    commonAction({
      url: '/server-work/action/workOrder/export/exportFields',
      method: 'post',
      data: { modelId: this.$route.params.modelId || this.$route.query.modelId }
    }).then(res1 => {
      if (res1.success) {
        this.businessList = []
        this.otherList = []
        this.checkedList = []
        if (res1.data) {
          res1.data.forEach(item => {
            if (['estimateStatus'].includes(item.fieldName)) {
              this.otherList.push(item.fieldName)
            } else {
              this.businessList.push(item.fieldName)
            }
            this.checkedList.push(item.fieldName)
          })
        }
      }
    })
  }

  private get busCategoryMap () {
    const obj = {}
    businessStore.busCategory.map(item => {
      obj[item.id] = item.modelName
    })
    return obj
  }

  private ordinaryFilterSearch (data) {
    this.filterSearch(data);
  }

  private filterSearch (data) {
    this.cacheFilter = cloneDeep(data);
    this.currentChangeFun(1);
  }

  // private filterSearchClose () {
  //   this.cacheFilter = {};
  // }

  private pageBack () {
    this.showPage = false
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private sizeChange (size: number) {
    this.queueTablePages.pageSize = size
    this.queryList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.queueTablePages.current = page
    this.queryList()
  }

  private handleDel (row: any) {
    const params = { id: row.id, modelId: row.modelId };
    if (this.currentFilterOpr) {
      Object.assign(params, { filterConfigId: this.currentFilterOpr.filterId })
    }
    (this.$confirm as any)('确定删除该条工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonAction({
        url: '/server-flow/action/instance/delete',
        method: 'post',
        data: params
      }).then(res => {
        if (res.success) {
          this.$message.success('删除工单成功')
          this.queryList()
        }
      })
    }).catch(e => {
      console.log(e)
    })
  }

  private handleEdit (obj: any) {
    this.dataInit()
    this.showPage = true
    this.$nextTick(() => {
      this.addOrEditBusinessRef.getBusinessDataById(obj, undefined, 'all')
    })
  }

  private handleReceive (obj: any) { // 领取工单
    commonAction({
      url: '/server-flow/action/task/claim',
      method: 'post',
      data: { workModelOrderId: obj.orderId, workModelId: obj.modelId, activityName: obj.activityName, activityId: obj.activityId }
    }).then(res => {
      if (res.success) {
        this.$message.success('领取工单成功')
        this.queryList()
      }
    })
  }

  private batchExportFun (selectedArr: any) {
    this.checkedList = []
    this.remark = ''
    this.otherList = []
    this.businessList = []
    this.checkAll = false
    this.tab = 1
    this.isIndeterminate = true
    this.selectedArr = selectedArr
    this.dialogVisible = true
  }

  private batchDelAgentFun (selectedArr: any) { // 批量删除
    this.$confirm('确定要批量删除工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let sendData = {}
      if (typeof selectedArr === 'object') { // 单个操作，传ids
        sendData = { operateCount: selectedArr.length, operateAll: false, recordIds: selectedArr || [], modelId: this.$route.params.modelId }
      } else { // 全选传查询条件
        sendData = {
          modelId: this.$route.params.modelId || this.$route.query.modelId,
          filters: this.cacheFilter,
          ...this.quickSearchForm.form,
          operateAll: true,
          operateCount: this.queueTablePages.total
        }
      }
      if (this.currentFilterOpr) {
        Object.assign(sendData, { filterConfigId: this.currentFilterOpr.filterId })
      }
      commonAction({
        url: '/server-flow/action/instance/batchDelete',
        method: 'post',
        data: sendData
      }).then(res => {
        if (res.success) {
          this.$message.success('批量删除工单成功')
          this.tableRef.cancelSelectFun() // 关闭批量操作栏
          this.queryList()
        }
      })
    })
  }

  private saveFun (type) {
    this.queryList(type)
    this.back()
  }

  private async queryList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.queueTablePages.current = 1
    }
    const params = {
      modelId: this.$route.params.modelId || this.$route.query.modelId,
      filters: this.cacheFilter,
      page: {
        pageNumber: this.queueTablePages.current,
        pageSize: this.queueTablePages.pageSize
      },
      ...this.quickSearchForm.form
    }
    if (this.currentFilterOpr) {
      Object.assign(params, { filterConfigId: this.currentFilterOpr.filterId })
    }
    if (!params.modelId) {
      return false
    }
    await commonAction({
      url: '/server-work/action/workOrder/list/category',
      method: 'post',
      data: { ...params }
    }).then(res => {
      if (res.success) {
        this.canDelete = this.currentFilterOpr.delete
        this.batchOperate = []
        if (this.canDelete) {
          this.batchOperate = [ // 批量操作设置
            { name: '批量删除', action: 'batchDelAgentFun', type: 'business' }
          ]
        }
        if (this.currentFilterOpr.export) {
          this.batchOperate.push({ name: '批量导出', action: 'batchExportFun', type: 'business' })
        }
        const list = res.data.workOrderList || []
        const total = res.data.page.total
        if (list.length === 0) {
          const page = Math.ceil(total / this.queueTablePages.pageSize)
          if (!total) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.queueTablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.queueTablePages.current = page
            this.queryList()
            return false
          }
        }
        list.forEach(item => {
          if (item.contactPhoneVO) {
            item.contactPhoneVO = ((item.contactPhoneVO.split(',')).map(v => checkHideTel(v))).join('、')
          }
          if (item.customerPhoneVO) {
            item.customerPhoneVO = ((item.customerPhoneVO.split(',')).map(v => checkHideTel(v))).join('、')
          }
          const agentObj = item.createUser && deepClone(CommonModule.publicCache.userListObj)[item.createUser]
          item.createUser = item.createUserName || (agentObj ? agentObj.name : '--')
          const agentObj1 = item.master && deepClone(CommonModule.publicCache.userListObj)[item.master]
          item.master = agentObj1 ? agentObj1.name : '--'
        })
        this.queueTableData = list
        this.queueTablePages.total = total
      }
    })
  }

  private back () {
    this.$nextTick(() => {
      // this.addOrEditBusinessRef.setQueueData()
      this.showPage = false
    })
  }

  // private beforeRouteEnter (to: any, from: any, next: any): void {
  //   next((vm) => {
  //     console.log('aaaa')
  //     vm.currentChangeFun(1)
  //   })
  // }

  @Watch('$route')
  private async routeChange (to: any, from: any) {
    if (this.$route.params.modelId) {
      if (to.query.orderId) { // 如果query有工单ID说明是详情跳转
        this.handleEdit(to.query)
      } else {
        this.quickSearchForm.form.orderNo = ''
        this.queueTablePages.pageSize = 10
        this.showPage = false
        if ((this.$refs as any).conditionFilterRef) {
          (this.$refs as any).conditionFilterRef.close()
        }
        // this.getConfig()
        this.cacheFilter = []
        this.tableRef.cancelSelectFun() // 关闭批量操作栏
        await this.filterRecordSearch()
        await this.getAllCol()
        await this.currentChangeFun(1)
      }
    }
  }

  // private getConfig () {
  //   commonAction({ url: '/server-work/action/workOrderModel/getConfig', method: 'post', data: { modelId: this.$route.params.modelId, queryFieldType: 2 } }).then(res => {
  //     if (res.success) {
  //       this.fields = res.data.fields || []
  //     }
  //   })
  // }

  private currentFilter (item) {
    this.cacheFilter = []
    this.currentFilterOpr = item
    this.tableRef.cancelSelectFun()
    this.queryList()
    this.getAllCol()
  }

  private async filterRecordSearch () {
    await commonAction({ url: '/server-work/action/filter/record/search', method: 'post', data: { modelId: this.$route.params.modelId || this.$route.query.modelId } }).then(res => {
      if (res.success) {
        this.filterArr = res.data.recordList
        // 默认进来点击第一个
        this.currentFilterOpr = res.data.recordList[0]
        this.isShowFilter = res.data.show
      }
    })
  }

  // 编辑工单
  private editWorkOrder () {
    this.isShowRule = false
    this.isOnlyShow = false
    this.filterBtn = true
  }

  // 取消工单
  private cancelWorkOrder () {
    this.isShowRule = true
    this.isOnlyShow = true
    this.filterBtn = false
  }

  // 更新工单
  private updateWorkOrder () {
    this.addOrEditBusinessRef.handleUpdate('', '编辑')
  }

  // 更新成功
  private editSuccess () {
    this.cancelWorkOrder()
    this.$message.success('成功！')
  }

  // 终止工单
  private TerminateWorkOrder () {
    this.$confirm('将工单终止后，该工单则不可进行流转，请确认是否要终止工单', '终止工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.addOrEditBusinessRef.update(null, 'allUpdate', '终止')
    })
  }

  // 调整当前处理人
  private transferWorkOrder () {
    this.addOrEditBusinessRef.AdjustmentHandler()
  }

  // 拖拽过滤器
  private onDragover (type) {
    const params = {
      modelId: this.$route.params.modelId,
      show: type,
      recordList: this.filterArr
    }
    commonAction({ url: '/server-work/action/filter/record/upsert', method: 'post', data: params }).then(res => {
      if (res.success) {
        this.isShowFilter = type
      }
    })
  }

  // 展开收起
  private expandCollapse () {
    this.onDragover(this.isShowFilter ? 0 : 1)
  }

  private getAllCol () {
    const req1 = commonAction({
      url: '/server-work/action/workOrderModel/getConfig',
      method: 'post',
      data: { modelId: this.$route.params.modelId || this.$route.query.modelId, queryFieldType: 2 }
    })
    const req2 = commonAction({
      url: '/server-work/action/view/search',
      method: 'post',
      data: { columnType: 5, modelId: this.$route.params.modelId || this.$route.query.modelId, filterConfigId: this.currentFilterOpr.filterId }
    })
    Promise.all([req1, req2]).then(res => {
      const res1 = res[0]
      const res2 = res[1]
      let customerCol: any[] = []
      if (res1.success) {
        this.fields = res1.data.fields || []
        const fieldType = ['text', 'multiText', 'radio', 'checkbox', 'region', 'sign', 'IntegerList', 'number', 'dateTime', 'member', 'department', 'accessory', 'cascadeSelect', 'associateService', 'associateSpare']
        this.customerFieldList = res1.data.fields.filter(item => {
          return fieldType.includes(item.fieldType) && !item.isSystem
        })
        const filterArr = ['associateService', 'associateSpare', 'associateUser', 'group', 'sign']
        customerCol = res1.data.fields.filter(item => {
          return !filterArr.includes(item.fieldType)
        }).map(item => {
          this.customColMap[item.businessId] = item
          return {
            businessId: item.businessId,
            label: item.name,
            prop: item.businessId,
            isShow: 0,
            show: false,
            customerField: true,
            field: item
          }
        })
      }
      if (res2.success) {
        // 第一次没保存表头列数据
        if (!res2.data) {
          this.queueTableHeader = this.originHeader.filter(item => item.show)
          this.queueTableHeader.unshift({ type: 'select' })
          this.queueTableHeader.push({ label: '操作', prop: 'oper', custom: true, fixed: 'right', width: '120px', align: 'center' })
          const row = this.originHeader.map(item => {
            item.businessId = item.prop
            item.isShow = item.show === true ? 1 : 0
            return item
          })
          const showRow = [...row, ...customerCol]
          this.customerTableHeader = [...showRow]
          commonAction({
            url: '/server-work/action/view/insert',
            method: 'post',
            data: { columnType: 5, showRow, modelId: this.$route.params.modelId || this.$route.query.modelId, filterConfigId: this.currentFilterOpr.filterId }
          }).then(res3 => {
            if (!res3.success) {
              this.$message.error('初始表格列失败')
            }
          })
        } else {
          const { showRow, id } = res2.data
          const showMap: any = {}
          this.originColId = id
          let saveRow: any[] = []
          saveRow = showRow.map(item => {
            showMap[item.businessId] = item
            return {
              field: this.customColMap[item.businessId],
              customerField: !!this.customColMap[item.businessId],
              prop: item.businessId,
              show: item.isShow === 1,
              label: this.colMap[item.businessId] ? this.colMap[item.businessId].label : this.customColMap[item.businessId] ? this.customColMap[item.businessId].name : '',
              custom: this.colMap[item.businessId] ? this.colMap[item.businessId].custom : false
            }
          })
          const tableRow = saveRow.filter(item => {
            return item.show
          })
          this.queueTableHeader = [...tableRow]
          this.queueTableHeader.unshift({ type: 'select' })
          this.queueTableHeader.push({ label: '操作', prop: 'oper', custom: true, fixed: 'right', width: '120px', align: 'center' })
          this.customerTableHeader = [...saveRow]
        }
      }
    })
  }

  // 初始化数据
  private dataInit () {
    // 默认规则开启
    this.isShowRule = true
    // 默认只读
    this.isOnlyShow = true
    this.filterBtn = false
  }

  private async beforeMount () {
    // 查询过滤器使用
    await this.filterRecordSearch()
    await this.getAllCol()
    // this.getConfig()
    await this.currentChangeFun(1)
    if (this.$route.query.modelId) {
      await this.handleEdit(this.$route.query)
    }
  }
}
</script>

<style lang="stylus" scoped>
.V7_iconV7tubiao_yidong {
  color: #B3B9C7;
  font-size: 12px;
  margin-right: 5px;
}
.list-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  width: 100%;
  span {
    line-height: 18px;
    flex: 1
  }
}
.padding-16 {
  padding: 16px
}
.tab-item {
  cursor pointer
}
.left-nav {
  display: flex;
  font-weight: 500;
  font-size: 12px;
  line-height: 18px;
  color: #303753;
  border-bottom: 1px solid  #E7E9ED
  div {
    margin 0px 16px
    line-height: 28px;
  }
  .tab-acitve {
    color: #008BEE;
    border-bottom: 1px solid #008bee;
  }
}
>>> .el-checkbox {
  display: block;
  margin-bottom: 8px;
}
.left, .right {
  width: 242px;
  height: 280px;
  background: #FFFFFF;
  border: 1px solid #E7E9ED;
  border-radius: 4px;
  overflow-y: auto;
}
.center {
  transform:rotate(-90deg)
  margin: 0px 10px
  color: #B3B9C7
}
>>> .el-dialog__wrapper .el-dialog .el-dialog__body {
  padding: 0px 24px 24px 24px;
}
.export-title {
  font-weight: 500;
  font-size: 12px;
  line-height: 18px;
  margin-bottom: 8px
}
.export-content {
  display: flex;
  align-items: center;
}
.opera-span {
  color $c-main
  margin-right 10px
  cursor pointer
}
.queue-wrap
  width 100%
  height 100%
  position relative
  /deep/ .hanle-wrapper-tree
    width 150px
    padding-left 2px
    padding-right 2px
  /deep/ .content
    position: relative
    padding: 0 22px 0;
  /deep/ .handle-wrapper-header
    padding: 16px 16px 0 22px;
  .is-show
    position: absolute;
    top: 45%;
    left: -1px;
  .icon-style
    font-size: 9px
    color: #767E91;
    border: 1px solid #E7E9ED;
    border-radius: 0px 8px 8px 0px;
    padding: 6px 3px;
    gap: 10px;
    cursor pointer
  .icon-style:hover
    color #008BEE
  .filter-item
    line-height: 20px
    .yidong-style
      opacity: 0
    .filter-name
      cursor: pointer
      margin-bottom: 22px
    .filter-name:hover .yidong-style
      opacity: 1 !important
.danger
  color $c-danger
.instiutionTable
  .overtime {
    color: #FC6B5C;
    border: 1px solid #FC6B5C;
    padding: 2px 4px;
    border-radius: 4px;
    font-weight: 500;
  }
  .noovertime {
    color: #2ED47A;
    border: 1px solid #2ED47A;
    padding: 2px 4px;
    border-radius: 4px;
    font-weight: 500
  }
  .unmatch {
    color: #B3B9C7;
    border: 1px solid #B3B9C7;
    padding: 2px 4px;
    border-radius: 4px;
    font-weight: 500;
  }
.active-filter
  font-family: 'PingFang SC'
  font-style: normal
  font-weight: 500
  font-size: 12px
  line-height: 18px
  color: #008BEE
.order-status {
  border-radius: 4px;
  border: 1px solid #B3B9C7;
  color: #B3B9C7
  padding: 1px 8px;
  font-size: 12px;
  line-height: 14px;
  height: 20px;
}
</style>
